import React, {useState} from "react";
import Ordertem from "./Ordertem.tsx";
import {Pressable, StyleProp, Text, useWindowDimensions, View, ViewStyle} from "react-native";
import {estimateTextHeight} from "../utils/estimateTextHeight.ts";
import {OrderColorMap, OrderIconsMap, OrderStatusMap} from "./OrderTypes.tsx";
import OrderItemButton from "./OrderItemButton.tsx";
import useStyles from "../useStyles.tsx";
import dayjs from "dayjs";
import ImageIcon from "../../components/ImageIcon.tsx";
import {useSelector} from "react-redux";
import {Icon} from "@rn-vui/themed";
import {useThemeColors} from "../../hooks/hooks.tsx";

interface OrderColumnProps {
    order?: any;
    style?: StyleProp<ViewStyle>;
    onSelectOrder?: (order: any) => void;
    onChooseOrder?: (order: any) => void;
    onMarkOrder?: (order: any) => void;
    onPressNote?: (order: any) => void;
    checked?: boolean;
    selected?: boolean;
    number?: number;
}

const OrderColumn = (props: OrderColumnProps) => {
    const {order} = props;
    const styles = useStyles();
    const colors = useThemeColors();
    const w = useWindowDimensions().width / 6;
    const h = useWindowDimensions().height - 250;
    const [columns, setColumns] = useState<any[]>([]);
    const variants = useSelector((state: any) => state.variants);

    const getFullTitle = (option: any) => {
        let title: string = option.value ? option.value : option;
        if (variants[title]) {
            const variant = variants[title];
            if (variant.name) {
                title += `(${variant.name})`;
            }
        }

        return '--' + title;
    }

    React.useEffect(() => {
        let newColumns: any[] = [[]];
        let columnHeight: number = 0;
        order.items?.forEach((item: any) => {
            let itemHeight: number = estimateTextHeight(item.title, 24, w);

            Object.values(item.variations).forEach((variant: any) => {
                if (variant !== null) {
                    const value = variant.value ? variant.value : variant;
                    if (!(/none/i.test(value) || /original/i.test(value))) {
                        itemHeight += estimateTextHeight(getFullTitle(variant), 22, w);
                    }
                }
            });

            item.options?.forEach((option: any) => {
                if (option) {
                    const value = option.value ? option.value : option;
                    if (!(/none/i.test(value) || /original/i.test(value))) {
                        itemHeight += estimateTextHeight(getFullTitle(option), 22, w);
                    }
                }
            });

            item.comments?.forEach((comment: any) => {
                if (comment && comment.name) {
                    const comment_name = comment.type + '-' + comment.name + (comment.name_cn ? '(' + comment.name_cn + ')' : '');
                    itemHeight += estimateTextHeight(comment_name + '--', 22, w);
                }
            });

            if (itemHeight + columnHeight > h) {
                newColumns.push([item]);
                columnHeight = itemHeight;
            } else {
                newColumns[newColumns.length - 1].push(item);
                columnHeight += itemHeight;
            }
        });

        //console.log('columns', newColumns);
        setColumns([...newColumns]);
    }, [order]);

    return (
        <View style={[
            styles.order,
            {
                maxWidth: w * columns.length
            },
            props.style
        ]}>
            <View style={styles.orderHeader}>
                <View>
                    <Text style={styles.orderN}>{order.short_code}</Text>
                    <Text style={styles.orderD}>{dayjs(order.created_at).format('MM/DD HH:mm')}</Text>
                </View>
                <View style={{maxWidth: '50%', minHeight: 65}}>
                    <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', gap: 5}}>
                        <ImageIcon source={OrderIconsMap[order.shipping_method]} size={30}/>
                        <Text style={styles.createVia}>{order.created_via}</Text>
                    </View>
                    <Text numberOfLines={3}
                          style={styles.shippingMethod}>{order.shipping_method_title}</Text>
                </View>
            </View>
            <Pressable
                onPress={() => props.onSelectOrder?.(order)}
                style={{
                    flex: 1,
                    flexDirection: 'row',
                    width: w * columns.length,
                    position: 'relative'
                }}
            >
                {
                    columns.map((column: any, index: number) => (
                        <View style={{width: w, rowGap: 5}} key={'column-' + index}>
                            {
                                column.map((item: any) => (
                                    <Ordertem
                                        key={'order-item-' + item.id}
                                        item={item}
                                    />
                                ))
                            }
                        </View>
                    ))
                }
                {
                    props.checked ? (
                        <View style={styles.checkMask}>
                            <Icon name={'check-circle'} color={colors.white} size={36}/>
                        </View>
                    ) : null
                }
                {
                    props.selected && !props.checked ? (
                        <View style={[styles.checkMask, {backgroundColor: 'rgba(0,0,0,0.3)'}]}></View>
                    ) : null
                }
            </Pressable>
            <OrderItemButton
                order={order}
                title={OrderStatusMap[order.dish_status]}
                color={OrderColorMap[order.dish_status]}
                status={order.dish_status}
                time={order.dish_time}
                checked={order.dish_marked}
                number={props.number}
                onPress={() => props.onChooseOrder?.(order)}
                onPressCheckbox={() => props.onMarkOrder?.(order)}
                onPressNote={() => props.onPressNote?.(order)}
            />
        </View>
    );
};

export default React.memo(OrderColumn);
